# -*-coding: utf-8 -*-
# by zw on 2017/12/27
from sanic import response

from utils.mongo import get_user_collection, get_usergroup_collection


class PERMISSION:
    dev = "dev"
    testenv = "testenv"

    prod = "prod"

    template = "template"
    global_template = "global_template"
    system = "system"


def permission_check(perm=""):
    def decorator(func):
        def wrapper(request, *args, **kwargs):
            if not request.path.split("/")[-1] in urls_before_login():
                if "user" not in request['session']:
                    # return response.json({"code": 403, "message": "not login ", "data": {}})
                    return response.redirect("/user/login.html?msg=%s" % ("not login!"))
                if (perm and perm not in request['session'].get("permission", [])) or not request['session'].get(
                        "permission", []):
                    # return response.json({"code": 403, "message": "lack permission ", "data": {}})
                    return response.redirect("/user/login.html?msg=%s" % ("lack permission!"))

            return func(request, *args, **kwargs)

        return wrapper

    return decorator


async def get_permission(user=None, request=None):
    if not user and request:
        username = request['session'].get("user")
        user = get_user_collection().find_one({"username": username}, )

    if not user or "group" not in user:
        return {}
    else:
        group = get_usergroup_collection().find_one({"group": user['group']}, )
        return {key: key for key in group['permission']}


def urls_before_login():
    return ["login.html", "register.html"]
